﻿#region Using directives
using System;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using AjaxControlToolkit;
using ProcolDemo.User;

#endregion

namespace ProcolDemo {
    public partial class MasterPage : System.Web.UI.MasterPage {
        public ModalPopupExtender PopupError {
            get { return modalError; }
        }

        protected void Page_Load(object sender, EventArgs e) {
            if (!Common.IsUserLoggedIn(Session))
                Response.Redirect("Default.aspx");

            int newLang;
            myprofil.HRef = String.Format("ViewProfile.aspx?Uid={0}", Common.GetUserId(Session));
            var userService = new UserService();
            var uidSession = Common.GetUserId(Session);

            // Change user language
            if (Request["lang"] != null && Int32.TryParse(Request["lang"], out newLang)) {
                var newUrl = String.Format("{0}?{1}LangChanged={2}", Request.Url.AbsolutePath,
                                           RemoveLangFromQueryString(), RandomString(10, true));
                userService.SetUserLanguage(Common.GetUserId(Session), newLang);

                Response.Redirect(newUrl, false);
                return;
            }

            int lang = Common.GetUserLanguage(uidSession);

            if (lang == 1) {
                usFlag.Src = "/images/us-en.png";
                mxFlag.Src = "/images/mx.png";
                deFlag.Src = "/images/de.png";
                mxLink.HRef = String.Format("?{0}lang=2", RemoveLangFromQueryString());
                deLink.HRef = String.Format("?{0}lang=3", RemoveLangFromQueryString());
            } else if (lang == 2) {
                mxFlag.Src = "/images/mx-en.png";
                usFlag.Src = "/images/us.png";
                deFlag.Src = "/images/de.png";
                usLink.HRef = String.Format("?{0}lang=1", RemoveLangFromQueryString());
                deLink.HRef = String.Format("?{0}lang=3", RemoveLangFromQueryString());
            } else if (lang == 3) {
                deFlag.Src = "/images/de-en.png";
                mxFlag.Src = "/images/mx.png";
                usFlag.Src = "/images/us.png";
                mxLink.HRef = String.Format("?{0}lang=2", RemoveLangFromQueryString());
                usLink.HRef = String.Format("?{0}lang=1", RemoveLangFromQueryString());
            }

            Common.FillI18NStrings(this, Session);

            userService.SetLastIp(uidSession, Context.Request.UserHostAddress);

            var RssLinks = new[] { RssGlobal, RssIdeas, RssProjects, RssSystem, RssMembers };

            foreach (var rss in RssLinks)
                rss.Attributes["href"] = String.Format("{0}&Uid={1}", rss.Attributes["href"], uidSession);
        }

        private String RemoveLangFromQueryString() {
            var query = Request.QueryString.ToString();
            query = Regex.Replace(query, @"lang=\d+", "");
            query = Regex.Replace(query, @"LangChanged=\w{10}", "");
            query = Regex.Replace(query, @"\?&", "?");
            query = Regex.Replace(query, @"&$", "");

            if (query.Length > 0)
                query += "&";

            query = Regex.Replace(query, @"&{2,}", "&");

            return query;
        }

        private static string RandomString(int size, bool lowerCase) {
            var builder = new StringBuilder();
            var random = new Random();

            for (int i = 0; i < size; i++) {
                char ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
                builder.Append(ch);
            }
            if (lowerCase)
                return builder.ToString().ToLower();
            return builder.ToString();
        }
    }
}